import sys

"""
一些基本的sql语句
"""
from xjlibrary.tools.BaseString import BaseString


def insert(table, datadict):
    sql = "INSERT INTO `" + table + "`" + insert_string_one(datadict)
    sql = sql_string_hook(sql)
    return sql


def update(table, datadict, wheredict):
    sql = "UPDATE `" + table + "`" + " SET " + set_string(datadict)
    if wheredict is not None and wheredict != {}:
        sql = sql + " WHERE " + where_string(wheredict)
    sql = sql_string_hook(sql)
    return sql


def set_string(datadict):
    result = ''
    for key, value in datadict:
        result = result + "`" + key + "`='" + value + "',"
    result = BaseString.r_strip_one_char(result)
    return result


def where_string(wheredict):
    result = ''
    for key, value in wheredict:
        result = result + "`" + key + "`='" + value + "' AND "
    result = BaseString.r_strip_char(result, 5)
    return result


def insert_string_one(datadict):
    if isinstance(datadict, dict):
        print(datadict)
        columna = "("
        varvalue = "("
        for key in datadict:
            columna += "`" + key + "`,"
            varvalue += "'" + datadict[key] + "',"
        columna = columna.rstrip(",")
        varvalue = varvalue.rstrip(",")
        columna += ")"
        varvalue += ")"
        print(columna + "VALUES" + varvalue)
        return columna + "VALUES" + varvalue
    else:
        raise ValueError("this data not is dict ,please check data at base_sql" + __file__ + sys._getframe().f_lineno)


def sql_string_hook(sql):
    print(sql)

    return sql
